package com.lagou.application;

import org.apache.catalina.Host;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Servlet;

/**
 * 创建人: yyn
 * 创建时间:2021/8/21 13:35
 */
public class SpringApplication {

    private Servlet servlet;

    private Class<?> main;

    public SpringApplication(Class<?> clazz) {
        this.main = clazz;
    }


    public static void run(Class<?> clazz, String... args) {
        new SpringApplication(clazz).run(args);
    }

    public void run(String... args) {
        System.out.println("启动");

        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();

        ac.register(main);

        ac.refresh();

        this.servlet = new DispatcherServlet(ac);

        createWebServer();


    }

    private void createWebServer() {
        Tomcat tomcat = new Tomcat();

        Connector connector = tomcat.getConnector();
        connector.setPort(8080);
        connector.setURIEncoding("UTF-8");


        Host host = tomcat.getHost();
        host.setAppBase("webapps");

        String classPath = System.getProperty("user.dir");
        tomcat.addContext(host, "/", classPath);
        Wrapper wrapper = tomcat.addServlet("/", "dispatcherServlet", servlet);
        wrapper.addMapping("/");
        try {
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

        tomcat.getServer().await();
    }
}
